package com.voxel.sense.infomsg.module.task.execution.report.details;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.entity.AbstractExpandableItem;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.TaskReportElementBean;
import com.voxel.sense.infomsg.data.bean.TaskReportHeadBean;
import com.voxel.sense.infomsg.utils.GlideUtils;
import com.voxel.sense.infomsg.view.holders.ExpandViewHolder;

import java.util.List;

import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.response.ReportEntity;

/**
 * @author ChenYiYao
 * @date 2018/5/14
 * des :
 */
public class ReportAdapter extends BaseMultiItemQuickAdapter<MultiItemEntity, ExpandViewHolder<MultiItemEntity>> {

    public ReportAdapter(List<MultiItemEntity> data) {
        super(data);
        addItemType(Constants.HEAD_TYPE, R.layout.item_recycler_expandable_head);
        addItemType(Constants.NORMAL_TYPE, R.layout.item_recycler_report);
    }

    @Override
    protected ExpandViewHolder<MultiItemEntity> onCreateDefViewHolder(ViewGroup parent, int viewType) {
        ExpandViewHolder holder;
        View inflate;
        if (viewType == Constants.NORMAL_TYPE) {
            inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_report, parent, false);
            holder = new ItemHolder(inflate);
        } else {
            inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_expandable_head, parent, false);
            holder = new HeadHolder(inflate);
        }

        return holder;
    }


    @Override
    protected void convert(ExpandViewHolder<MultiItemEntity> helper, MultiItemEntity item) {
        if (item.getItemType() == Constants.HEAD_TYPE) {
            helper.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int adapterPosition = helper.getAdapterPosition();
                    if (((AbstractExpandableItem) item).isExpanded()) {
                        collapse(adapterPosition, false);
                        helper.changeExpandIcon(R.mipmap.ic_drop_selected_icon);
                    } else {
                        expand(adapterPosition, false);
                        helper.changeExpandIcon(R.mipmap.ic_drop_unselected_icon);
                    }
                }
            });
        } else if (item.getItemType() == Constants.HEAD_TYPE) {
        }
        helper.onBind(item);

    }

    static class HeadHolder extends ExpandViewHolder<TaskReportHeadBean> {
        TextView title;
        ImageView iv_icon;

        public HeadHolder(View view) {
            super(view);
            title = itemView.findViewById(R.id.title);
            iv_icon = itemView.findViewById(R.id.iv_icon);
        }


        @Override
        public void onBind(TaskReportHeadBean bean) {
            title.setText(bean.getDesc());
            int resId = (bean.isExpanded()) ? R.mipmap.ic_drop_selected_icon : R.mipmap.ic_drop_unselected_icon;
            changeExpandIcon(resId);
        }

        @Override
        public void changeExpandIcon(int id) {
            GlideUtils.GlideFitCenterLoadPic(iv_icon.getContext(), id, iv_icon);
        }
    }


    static class ItemHolder extends ExpandViewHolder<TaskReportElementBean> {
        TextView tv_desc;
        RadioGroup rg_two;
        RadioButton rb_yes;
        RadioButton rb_no;
        //三个选项的复选框
        RadioGroup rg_tree;
        RadioButton rb_none;
        RadioButton rb_finish;
        RadioButton rb_unfinish;

        EditText et_result;
        EditText et_note;
        LinearLayout ll_note;
        private RadioGroup.OnCheckedChangeListener mRgTreeChangeListener;
        private RadioGroup.OnCheckedChangeListener mRgTwoChangeListener;

        public ItemHolder(View view) {
            super(view);
            tv_desc = view.findViewById(R.id.tv_desc);
            rg_two = view.findViewById(R.id.rg_two);
            rb_yes = view.findViewById(R.id.rb_yes);
            rb_no = view.findViewById(R.id.rb_no);
            rg_tree = view.findViewById(R.id.rg_tree);
            rb_none = view.findViewById(R.id.rb_none);
            rb_finish = view.findViewById(R.id.rb_finish);
            rb_unfinish = view.findViewById(R.id.rb_unfinish);
            et_result = view.findViewById(R.id.et_result);
            et_note = view.findViewById(R.id.et_note);
            ll_note = view.findViewById(R.id.ll_note);
        }


        @Override
        public void onBind(TaskReportElementBean bean) {
            ReportEntity.FormElementListBean element = bean.getBean();
            ReportEntity.FormElementListBean.ValueGroupBean valueGroup = bean.getBean().getValueGroup();
            //若是记录值的实体为空时，先创建一个实体
            if (valueGroup == null) {
                valueGroup = new ReportEntity.FormElementListBean.ValueGroupBean();
                bean.getBean().setValueGroup(valueGroup);
            }


            tv_desc.setText(element.getEleContent());

            //设置item是否状态
            setItemStatus(bean.isEnable());
            //这里先移除radioGroup的监听，避免复用时初始化值时，调用onCheckedChanged监听
            removeRadioBtnEvent();
            //初始化单选按钮
            String selectValue = valueGroup.getSelectValue();
            initRadioGroup(element, selectValue);
            //单选按钮事件
            BtnToggleEvent(bean);


            //判断是否有备注选项
            if ("1".equals(bean.getParam1())) {
                ll_note.setVisibility(View.VISIBLE);
            } else {
                ll_note.setVisibility(View.GONE);
            }

            et_result.setText(valueGroup.getResultRecord());
            et_note.setText(valueGroup.getRemark());

            //结果输入框事件
            setResultListener(bean);
            //备注输入事件
            setNoteListener(bean);

        }

        /**
         * 设置各个view是否可用
         *
         * @param b
         */
        private void setItemStatus(boolean b) {
            for (int i = 0; i < rg_tree.getChildCount(); i++) {
                rg_tree.getChildAt(i).setClickable(b);
            }
            for (int i = 0; i < rg_two.getChildCount(); i++) {
                rg_two.getChildAt(i).setClickable(b);
            }
            et_note.setEnabled(b);
            et_result.setEnabled(b);
        }

        //初始化单选按钮
        private void initRadioGroup(ReportEntity.FormElementListBean element, String selectValue) {
            //根据条件判断筛选条件是几个按钮
            //1 为双选按钮， 2 为三个选项的单选
            if ("1".equals(element.getEleInputStatus())) {
                rg_two.setVisibility(View.VISIBLE);
                rg_tree.setVisibility(View.GONE);
                //这里先进行清除radiogroup的状态。不然有时会导致setChecked设置选中状态时，界面没有刷新的情况。
                //未找出具体原因
                rg_two.clearCheck();
                if ("1".equals(selectValue)) {
                    rb_yes.setChecked(true);
                } else if ("2".equals(selectValue)) {
                    rb_no.setChecked(true);
                } else {
                    //没有值
                    rb_yes.setChecked(false);
                }
            } else if ("2".equals(element.getEleInputStatus())) {
                rg_two.setVisibility(View.GONE);
                rg_tree.setVisibility(View.VISIBLE);
                rg_tree.clearCheck();
                if ("1".equals(selectValue)) {
                    rb_none.setChecked(true);
                } else if ("2".equals(selectValue)) {
                    rb_finish.setChecked(true);
                } else if ("3".equals(selectValue)) {
                    rb_unfinish.setChecked(true);
                } else {
                    rb_finish.setChecked(false);
                    rb_none.setChecked(false);
                    rb_unfinish.setChecked(false);
                }
            } else {
                rg_two.setVisibility(View.GONE);
                rg_tree.setVisibility(View.GONE);
            }
        }

        private void BtnToggleEvent(TaskReportElementBean bean) {
            mRgTwoChangeListener = new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    ReportEntity.FormElementListBean.ValueGroupBean valueBean = bean.getBean().getValueGroup();
                    if (checkedId == R.id.rb_yes) {
                        String value = rb_yes.isChecked() ? "1" : "";
                        valueBean.setSelectValue(value);
                    } else if (checkedId == R.id.rb_no) {
                        String value = rb_no.isChecked() ? "2" : "";
                        valueBean.setSelectValue(value);
                    }
                }
            };
            rg_two.setOnCheckedChangeListener(mRgTwoChangeListener);

            mRgTreeChangeListener = new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    ReportEntity.FormElementListBean.ValueGroupBean valueBean = bean.getBean().getValueGroup();
                    if (checkedId == R.id.rb_none) {
                        String value = rb_none.isChecked() ? "1" : "";
                        valueBean.setSelectValue(value);
                    } else if (checkedId == R.id.rb_finish) {
                        String value = rb_finish.isChecked() ? "2" : "";
                        valueBean.setSelectValue(value);
                    } else if (checkedId == R.id.rb_unfinish) {
                        String value = rb_unfinish.isChecked() ? "3" : "";
                        valueBean.setSelectValue(value);
                    }
                }
            };
            rg_tree.setOnCheckedChangeListener(mRgTreeChangeListener);
        }

        /**
         * 移除radio的监听
         */
        private void removeRadioBtnEvent() {
            if (mRgTreeChangeListener != null) {
                rg_tree.setOnCheckedChangeListener(null);
            }
            if (mRgTwoChangeListener != null) {
                rg_two.setOnCheckedChangeListener(null);
            }
        }


        private void setResultListener(TaskReportElementBean bean) {
            TextWatcher textWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    ReportEntity.FormElementListBean.ValueGroupBean valueGroup = bean.getBean().getValueGroup();
                    if (valueGroup != null) {
                        valueGroup.setResultRecord(s.toString());
                    } else {
                        valueGroup = new ReportEntity.FormElementListBean.ValueGroupBean();
                        valueGroup.setResultRecord(s.toString());
                        bean.getBean().setValueGroup(valueGroup);

                    }

                }
            };


            et_result.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    //设置焦点监听，只有获取到焦点才监听内容变化，以防复用view赋值时触发
                    if (hasFocus) {
                        et_result.addTextChangedListener(textWatcher);
                    } else {
                        et_result.removeTextChangedListener(textWatcher);

                    }
                }
            });
            et_result.clearFocus();
        }


        private void setNoteListener(TaskReportElementBean bean) {
            TextWatcher textWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    ReportEntity.FormElementListBean.ValueGroupBean valueGroup = bean.getBean().getValueGroup();
                    if (valueGroup != null) {
                        valueGroup.setRemark(s.toString());
                    } else {
                        valueGroup = new ReportEntity.FormElementListBean.ValueGroupBean();
                        valueGroup.setRemark(s.toString());
                        bean.getBean().setValueGroup(valueGroup);

                    }

                }
            };


            et_note.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    //设置焦点监听，只有获取到焦点才监听内容变化，以防复用view赋值时触发

                    if (hasFocus) {
                        et_note.addTextChangedListener(textWatcher);
                    } else {
                        et_note.removeTextChangedListener(textWatcher);

                    }
                }
            });
            et_note.clearFocus();
        }


        @Override
        public void changeExpandIcon(int id) {

        }
    }

}
